import { Card, Row, Col, Statistic, Table, Tag, Progress, message } from 'antd'
import { useState, useEffect } from 'react'
import './AdminDashboard.css'
import {
    UserOutlined,
    BookOutlined,
    EyeOutlined,
    HeartOutlined,
    TrophyOutlined,
    RiseOutlined
} from '@ant-design/icons'
import { getUserStats, getRecentUsers } from '../../api/user'
import { getDictStats, getPopularDicts } from '../../api/dict'
import dayjs from 'dayjs'

export default function AdminDashboard() {
    const [stats, setStats] = useState({
        totalUsers: 0,
        totalTemplates: 0,
        todayUsers: 0,
        todayTemplates: 0
    })

    const [recentUsers, setRecentUsers] = useState([])
    const [popularTemplates, setPopularTemplates] = useState([])
    const [loading, setLoading] = useState(true)

    // 获取统计数据
    const fetchStats = async () => {
        try {
            const [userStatsRes, dictStatsRes] = await Promise.all([
                getUserStats(),
                getDictStats()
            ])

            if (userStatsRes.data.code === 0 && dictStatsRes.data.code === 0) {
                setStats({
                    totalUsers: userStatsRes.data.data.totalUsers || 0,
                    totalTemplates: dictStatsRes.data.data.totalTemplates || 0,
                    todayUsers: userStatsRes.data.data.todayUsers || 0,
                    todayTemplates: dictStatsRes.data.data.todayTemplates || 0
                })
            }
        } catch (error) {
            console.error('获取统计数据失败:', error)
            message.error('获取统计数据失败')
        }
    }

    // 获取最近用户
    const fetchRecentUsers = async () => {
        try {
            const response = await getRecentUsers(5)
            if (response.data.code === 0) {
                setRecentUsers(response.data.data || [])
            }
        } catch (error) {
            console.error('获取最近用户失败:', error)
        }
    }

    // 获取热门模板
    const fetchPopularTemplates = async () => {
        try {
            const response = await getPopularDicts(5)
            if (response.data.code === 0) {
                setPopularTemplates(response.data.data || [])
            }
        } catch (error) {
            console.error('获取热门模板失败:', error)
        }
    }

    useEffect(() => {
        const loadData = async () => {
            setLoading(true)
            await Promise.all([
                fetchStats(),
                fetchRecentUsers(),
                fetchPopularTemplates()
            ])
            setLoading(false)
        }
        loadData()
    }, [])

    const userColumns = [
        {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
            render: (text) => text || '未设置'
        },
        {
            title: '账号',
            dataIndex: 'userAccount',
            key: 'userAccount',
        },
        {
            title: '角色',
            dataIndex: 'userRole',
            key: 'userRole',
            render: (role) => (
                <Tag color={role === 'admin' ? 'red' : 'blue'}>
                    {role === 'admin' ? '管理员' : '普通用户'}
                </Tag>
            ),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={status === 1 ? 'green' : 'red'}>
                    {status === 1 ? '正常' : '禁用'}
                </Tag>
            ),
        },
        {
            title: '注册时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'
        },
    ]

    const templateColumns = [
        {
            title: '模板名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            render: (category) => <Tag color="purple">{category}</Tag>,
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags',
            render: (tags) => {
                if (!tags) return '-'
                try {
                    const tagList = JSON.parse(tags)
                    return tagList.slice(0, 2).map(tag => (
                        <Tag key={tag} size="small">{tag}</Tag>
                    ))
                } catch {
                    return '-'
                }
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-'
        },
    ]

    return (
        <div className="admin-dashboard">
            <div className="dashboard-header">
                <h1 className="dashboard-title">仪表盘</h1>
                <p className="dashboard-subtitle">欢迎回到 PromptCraft 管理系统</p>
            </div>

            {/* 统计卡片 */}
            <Row gutter={[24, 24]} className="stats-row">
                <Col xs={24} sm={12} lg={6}>
                    <Card className="stat-card stat-card-users" loading={loading}>
                        <Statistic
                            title="总用户数"
                            value={stats.totalUsers}
                            prefix={<UserOutlined />}
                            valueStyle={{ color: '#1890ff' }}
                        />
                        <div className="stat-trend">
                            <span style={{ color: '#666' }}>今日新增: {stats.todayUsers}</span>
                        </div>
                    </Card>
                </Col>
                <Col xs={24} sm={12} lg={6}>
                    <Card className="stat-card stat-card-templates" loading={loading}>
                        <Statistic
                            title="模板总数"
                            value={stats.totalTemplates}
                            prefix={<BookOutlined />}
                            valueStyle={{ color: '#722ed1' }}
                        />
                        <div className="stat-trend">
                            <span style={{ color: '#666' }}>今日新增: {stats.todayTemplates}</span>
                        </div>
                    </Card>
                </Col>
            </Row>

            {/* 数据表格 */}
            <Row gutter={[24, 24]} className="tables-row">
                <Col xs={24} lg={12}>
                    <Card 
                        title={
                            <div className="card-title">
                                <UserOutlined />
                                <span>最近注册用户</span>
                            </div>
                        }
                        className="data-card"
                    >
                        <Table
                            columns={userColumns}
                            dataSource={recentUsers}
                            pagination={false}
                            size="small"
                            rowKey="id"
                            loading={loading}
                        />
                    </Card>
                </Col>
                <Col xs={24} lg={12}>
                    <Card 
                        title={
                            <div className="card-title">
                                <TrophyOutlined />
                                <span>热门模板</span>
                            </div>
                        }
                        className="data-card"
                    >
                        <Table
                            columns={templateColumns}
                            dataSource={popularTemplates}
                            pagination={false}
                            size="small"
                            rowKey="id"
                            loading={loading}
                        />
                    </Card>
                </Col>
            </Row>
        </div>
    )
}
